package com.shujia.flink.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author shujia
 */
public class DateUtils {

    /**
     * 将时间字符串转换成时间戳
     *
     * @param str 时间字符串
     * @return 毫秒级别的时间戳
     */
    public static long stringToTimestamp(String str, String format) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
        long ts = 0;
        try {
            Date parse = simpleDateFormat.parse(str);
            ts = parse.getTime();
        } catch (ParseException ignored) {
        }
        return ts;
    }

    public static long stringToTimestamp(String str) {
        return stringToTimestamp(str, "yyyy-MM-dd HH:mm:ss");
    }

    /**
     * 将时间戳转换成时间字符串
     *
     * @param ts 毫秒时间戳
     * @return 返回时间字符串
     */
    public static String timestampToString(Long ts, String format) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
        Date date = new Date(ts);
        return simpleDateFormat.format(date);
    }

    public static String timestampToString(Long ts) {
        return timestampToString(ts, "yyyy-MM-dd HH:mm:ss");
    }
}
